import 'dart:async';
import 'package:flutter/foundation.dart';

/// 缓存服务接口，用于依赖注入
abstract class CacheService {
  Future<void> startCache(String url);
  Future<void> stopCache(String url);
}

/// 缓存稳定性管理器（优化版本）
/// 处理重试机制和基本的异常恢复
class CacheStabilityManager {
  static CacheStabilityManager? _instance;
  static CacheStabilityManager get instance =>
      _instance ??= CacheStabilityManager._();

  CacheStabilityManager._();

  // 依赖注入的缓存服务
  CacheService? _cacheService;

  // 重试机制
  final Map<String, RetryContext> _retryContexts = {};
  Timer? _retryTimer;

  bool _isInitialized = false;

  // 配置参数
  static const Duration retryInterval = Duration(seconds: 30);
  static const int maxRetryAttempts = 3;

  /// 设置缓存服务（依赖注入）
  void setCacheService(CacheService cacheService) {
    _cacheService = cacheService;
  }

  /// 初始化稳定性管理器
  Future<void> initialize({int? maxRetries, Duration? retryDelay}) async {
    if (_isInitialized) return;

    // 如果提供了参数，更新配置（这里为简化实现，使用静态常量）
    if (maxRetries != null) {
      debugPrint(
          'CacheStabilityManager: 设置最大重试次数 - $maxRetries (当前使用默认值 $maxRetryAttempts)');
    }
    if (retryDelay != null) {
      debugPrint(
          'CacheStabilityManager: 设置重试延迟 - $retryDelay (当前使用默认值 $retryInterval)');
    }

    _initRetryMechanism();

    _isInitialized = true;
    debugPrint('CacheStabilityManager: 初始化完成');
  }

  /// 初始化重试机制
  void _initRetryMechanism() {
    _retryTimer = Timer.periodic(retryInterval, (_) {
      _processRetries();
    });
  }

  /// 注册缓存任务（用于重试管理）
  void registerCacheTask(String url) {
    _retryContexts[url] = RetryContext(
      url: url,
      attempts: 0,
      lastAttempt: DateTime.now(),
      isActive: true,
    );

    debugPrint('CacheStabilityManager: 注册缓存任务 - $url');
  }

  /// 缓存任务成功
  void onCacheSuccess(String url) {
    _retryContexts.remove(url);
    debugPrint('CacheStabilityManager: 缓存任务成功 - $url');
  }

  /// 缓存任务失败
  void onCacheFailure(String url, String error) {
    final context = _retryContexts[url];
    if (context != null) {
      context.attempts++;
      context.lastError = error;
      context.lastAttempt = DateTime.now();
      context.isActive = false;

      debugPrint(
          'CacheStabilityManager: 缓存任务失败 - $url (第${context.attempts}次失败): $error');

      if (context.attempts >= maxRetryAttempts) {
        debugPrint('CacheStabilityManager: 缓存任务达到最大重试次数，放弃 - $url');
        _retryContexts.remove(url);
      }
    }
  }

  /// 处理重试逻辑
  void _processRetries() {
    final now = DateTime.now();
    final urlsToRetry = <String>[];

    _retryContexts.forEach((url, context) {
      if (!context.isActive &&
          context.attempts < maxRetryAttempts &&
          now.difference(context.lastAttempt) >= retryInterval) {
        urlsToRetry.add(url);
      }
    });

    for (final url in urlsToRetry) {
      _retryCache(url);
    }
  }

  /// 重试缓存任务
  void _retryCache(String url) {
    final context = _retryContexts[url];
    if (context == null) return;

    if (_cacheService == null) {
      debugPrint('CacheStabilityManager: 缓存服务未设置，无法重试 - $url');
      return;
    }

    context.isActive = true;
    context.lastAttempt = DateTime.now();

    debugPrint(
        'CacheStabilityManager: 重试缓存任务 - $url (第${context.attempts + 1}次尝试)');

    try {
      _cacheService!.startCache(url).then((_) {
        onCacheSuccess(url);
      }).catchError((error) {
        onCacheFailure(url, error.toString());
      });
    } catch (e) {
      onCacheFailure(url, e.toString());
    }
  }

  /// 手动重启失败的缓存（可由用户或其他管理器调用）
  void retryFailedCaches() {
    final failedUrls = _retryContexts.entries
        .where((entry) => !entry.value.isActive)
        .map((entry) => entry.key)
        .toList();

    debugPrint('CacheStabilityManager: 手动重启${failedUrls.length}个失败的缓存任务');

    for (final url in failedUrls) {
      _retryCache(url);
    }
  }

  /// 停止所有活跃的缓存任务
  void stopAllActiveCaches() {
    debugPrint('CacheStabilityManager: 停止所有活跃缓存任务');

    if (_cacheService == null) {
      debugPrint('CacheStabilityManager: 缓存服务未设置，无法停止缓存任务');
      return;
    }

    _retryContexts.forEach((url, context) {
      if (context.isActive) {
        context.isActive = false;
        try {
          _cacheService!.stopCache(url);
        } catch (e) {
          debugPrint('CacheStabilityManager: 停止缓存失败 - $url: $e');
        }
      }
    });
  }

  /// 获取稳定性统计
  Map<String, dynamic> getStabilityStats() {
    final activeRetries =
        _retryContexts.values.where((context) => context.isActive).length;
    final failedRetries =
        _retryContexts.values.where((context) => !context.isActive).length;

    return {
      'totalRetryContexts': _retryContexts.length,
      'activeRetries': activeRetries,
      'failedRetries': failedRetries,
      'maxRetryAttempts': maxRetryAttempts,
    };
  }

  /// 带重试机制的缓存方法（测试和示例专用API）
  Future<void> cacheWithRetry(String url) async {
    if (_cacheService == null) {
      throw StateError('缓存服务未设置，请先调用setCacheService()');
    }

    registerCacheTask(url);

    try {
      await _cacheService!.startCache(url);
      onCacheSuccess(url);
    } catch (e) {
      onCacheFailure(url, e.toString());
      rethrow; // 重新抛出异常，让调用者知道首次尝试失败
    }
  }

  /// 获取健康报告（测试和示例专用API）
  Map<String, dynamic> getHealthReport() {
    final totalTasks = _retryContexts.length;
    const successfulTasks = 0; // 成功的任务会被移除，所以这里是0
    final failedTasks =
        _retryContexts.values.where((context) => !context.isActive).length;
    final retriedTasks =
        _retryContexts.values.where((context) => context.attempts > 0).length;

    final failureRate = totalTasks > 0 ? failedTasks / totalTasks : 0.0;

    return {
      'successfulTasks': successfulTasks,
      'failedTasks': failedTasks,
      'retriedTasks': retriedTasks,
      'totalTasks': totalTasks,
      'failureRate': failureRate,
      'maxRetryAttempts': maxRetryAttempts,
      'retryInterval': retryInterval.inSeconds,
    };
  }

  /// 取消注册缓存任务
  void unregisterCacheTask(String url) {
    _retryContexts.remove(url);
    debugPrint('CacheStabilityManager: 取消注册缓存任务 - $url');
  }

  /// 释放所有资源
  void dispose() {
    if (!_isInitialized) return;

    _retryTimer?.cancel();
    _retryTimer = null;

    _retryContexts.clear();

    _isInitialized = false;
    debugPrint('CacheStabilityManager: 资源释放完成');
  }

  // Getters
  int get activeRetryCount =>
      _retryContexts.values.where((context) => context.isActive).length;
  int get failedRetryCount =>
      _retryContexts.values.where((context) => !context.isActive).length;
  List<String> get failedUrls => _retryContexts.entries
      .where((entry) => !entry.value.isActive)
      .map((entry) => entry.key)
      .toList();
}

/// 重试上下文
class RetryContext {
  final String url;
  int attempts;
  DateTime lastAttempt;
  bool isActive;
  String? lastError;

  RetryContext({
    required this.url,
    required this.attempts,
    required this.lastAttempt,
    required this.isActive,
    this.lastError,
  });

  @override
  String toString() =>
      'RetryContext(url: $url, attempts: $attempts, isActive: $isActive, lastError: $lastError)';
}
